/**
 * 
 */
package zookeeper.lock;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;

/**
 * @author tianping.czp
 * 
 */
public class TestLock {
	
	private static ZooKeeper zk;
	private static String HOST_PORT = "127.0.0.1:2181";
	
	static {
		try {
			zk = new ZooKeeper(HOST_PORT, 3000, null);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		//WriteLock lock = new WriteLock(zk, ZNODE, Ids.OPEN_ACL_UNSAFE,new DefaultLockListener());
		ExecutorService es = Executors.newFixedThreadPool(5);
		for (int i=0; i < 5 ;i ++){
			es.execute(new LockFinder(i,zk));
		}
		es.shutdown();
	}
}

class LockFinder implements Runnable {
	
	private WriteLock lock;
	private int threadId;
	
	
	private static String ZNODE = "/tianping";
	
	public LockFinder( int threadId, ZooKeeper zk) {
		this.threadId = threadId;
		//this.lock = new WriteLock(zk, ZNODE, Ids.OPEN_ACL_UNSAFE,new DefaultLockListener(this.threadId));
		this.lock = new WriteLock(zk, ZNODE, Ids.OPEN_ACL_UNSAFE,null);
	}

	@Override
	public void run() {
		try {
			System.out.println("before lock id : " + threadId);
			while(!lock.lock());
			System.out.println("lock id : " + threadId);
			Thread.sleep(1000);
		} catch (KeeperException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally{
			lock.unlock();
			System.out.println("unlock id : " + threadId);
		}
	}
}

class DefaultLockListener implements LockListener{
	
	private int id;
	
	public DefaultLockListener(int id) {
		this.id = id;
	}

	@Override
	public void lockAcquired() {
		System.out.println("lock id : " + id);
	}

	@Override
	public void lockReleased() {
		System.out.println("unlock id : " + id);
	}
	
}
